import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import type { 
  RecoveryTask, 
  RecoveryResult, 
  BatchRecoveryResult,
  RecoveryOptions,
  BatchRecoveryOptions,
  RecoveryPreview,
  ConflictInfo 
} from '../types/basic'
import { recoveryEngine } from '../services'

export const useRecoveryStore = defineStore('recovery', () => {
  // State
  const recoveryQueue = ref<RecoveryTask[]>([])
  const completedRecoveries = ref<RecoveryResult[]>([])
  const failedRecoveries = ref<RecoveryResult[]>([])
  const isRecovering = ref(false)
  const currentTask = ref<RecoveryTask | null>(null)
  const progress = ref(0)
  const totalTasks = ref(0)
  const error = ref<string | null>(null)
  const recoveryHistory = ref<BatchRecoveryResult[]>([])
  
  // Recovery options
  const defaultOptions = ref<RecoveryOptions>({
    overwrite: false,
    createDirectories: true,
    preserveTimestamp: true
  })
  
  const batchOptions = ref<BatchRecoveryOptions>({
    ...defaultOptions.value,
    continueOnError: true,
    maxConcurrent: 3
  })

  // Preview data
  const previewData = ref<RecoveryPreview | null>(null)
  const conflicts = ref<ConflictInfo[]>([])

  // Services - use the configured instance

  // Getters
  const hasQueuedTasks = computed(() => recoveryQueue.value.length > 0)
  
  const hasCompletedTasks = computed(() => completedRecoveries.value.length > 0)
  
  const hasFailedTasks = computed(() => failedRecoveries.value.length > 0)
  
  const successRate = computed(() => {
    const total = completedRecoveries.value.length + failedRecoveries.value.length
    return total > 0 ? (completedRecoveries.value.length / total) * 100 : 0
  })
  
  const queueSummary = computed(() => ({
    total: recoveryQueue.value.length,
    pending: recoveryQueue.value.length,
    completed: completedRecoveries.value.length,
    failed: failedRecoveries.value.length
  }))

  const recentRecoveries = computed(() => 
    recoveryHistory.value.slice(-10).reverse()
  )

  // Actions
  function addToQueue(task: RecoveryTask) {
    // Check if task already exists
    const exists = recoveryQueue.value.some(t => 
      t.versionId === task.versionId && 
      t.fileId === task.fileId && 
      t.targetPath === task.targetPath
    )
    
    if (!exists) {
      recoveryQueue.value.push(task)
    }
  }

  function addMultipleToQueue(tasks: RecoveryTask[]) {
    tasks.forEach(task => addToQueue(task))
  }

  function removeFromQueue(index: number) {
    if (index >= 0 && index < recoveryQueue.value.length) {
      recoveryQueue.value.splice(index, 1)
    }
  }

  function clearQueue() {
    if (!isRecovering.value) {
      recoveryQueue.value = []
    }
  }

  async function recoverSingle(task: RecoveryTask, options?: Partial<RecoveryOptions>) {
    try {
      isRecovering.value = true
      currentTask.value = task
      error.value = null
      
      const mergedOptions = { ...defaultOptions.value, ...options }
      const result = await recoveryEngine.recoverFile(
        task.versionId,
        task.fileId,
        task.targetPath,
        mergedOptions
      )
      
      if (result.success) {
        completedRecoveries.value.push(result)
      } else {
        failedRecoveries.value.push(result)
      }
      
      return result
    } catch (err) {
      const errorResult: RecoveryResult = {
        success: false,
        targetPath: task.targetPath,
        error: err instanceof Error ? err.message : '恢复失败',
        bytesWritten: 0
      }
      
      failedRecoveries.value.push(errorResult)
      error.value = errorResult.error!
      return errorResult
    } finally {
      isRecovering.value = false
      currentTask.value = null
    }
  }

  async function recoverBatch(options?: Partial<BatchRecoveryOptions>): Promise<BatchRecoveryResult | undefined> {
    if (recoveryQueue.value.length === 0) {
      error.value = '恢复队列为空'
      return undefined
    }

    try {
      isRecovering.value = true
      error.value = null
      progress.value = 0
      totalTasks.value = recoveryQueue.value.length
      
      const mergedOptions = { ...batchOptions.value, ...options }
      const tasksToRecover = [...recoveryQueue.value]
      
      // Clear queue before starting
      recoveryQueue.value = []
      
      const result = await recoveryEngine.batchRecover(tasksToRecover, mergedOptions)
      
      // Update results
      completedRecoveries.value.push(...result.successful)
      failedRecoveries.value.push(...result.failed)
      
      // Add to history
      recoveryHistory.value.push(result)
      
      // Keep only last 100 history entries
      if (recoveryHistory.value.length > 100) {
        recoveryHistory.value = recoveryHistory.value.slice(-100)
      }
      
      return result
    } catch (err) {
      error.value = err instanceof Error ? err.message : '批量恢复失败'
      console.error('Batch recovery failed:', err)
      return undefined
    } finally {
      isRecovering.value = false
      progress.value = 0
      totalTasks.value = 0
      currentTask.value = null
    }
  }

  async function previewRecovery(tasks?: RecoveryTask[]): Promise<RecoveryPreview | undefined> {
    const tasksToPreview = tasks || recoveryQueue.value
    
    if (tasksToPreview.length === 0) {
      previewData.value = null
      conflicts.value = []
      return undefined
    }

    try {
      const preview = await recoveryEngine.previewRecovery(tasksToPreview)
      previewData.value = preview
      conflicts.value = preview.conflicts
      return preview
    } catch (err) {
      error.value = err instanceof Error ? err.message : '预览恢复失败'
      console.error('Preview recovery failed:', err)
      return undefined
    }
  }

  function updateProgress(completed: number, total: number) {
    progress.value = total > 0 ? (completed / total) * 100 : 0
  }

  function updateDefaultOptions(options: Partial<RecoveryOptions>) {
    defaultOptions.value = { ...defaultOptions.value, ...options }
  }

  function updateBatchOptions(options: Partial<BatchRecoveryOptions>) {
    batchOptions.value = { ...batchOptions.value, ...options }
  }

  function clearResults() {
    completedRecoveries.value = []
    failedRecoveries.value = []
  }

  function clearHistory() {
    recoveryHistory.value = []
  }

  function retryFailed() {
    const failedTasks = failedRecoveries.value
      .filter(result => !result.success)
      .map(result => ({
        versionId: '', // This would need to be stored in the result
        fileId: '',    // This would need to be stored in the result
        originalPath: '',
        targetPath: result.targetPath
      }))
    
    // Add failed tasks back to queue
    addMultipleToQueue(failedTasks)
    
    // Clear failed results
    failedRecoveries.value = []
  }

  function removeCompletedResult(index: number) {
    if (index >= 0 && index < completedRecoveries.value.length) {
      completedRecoveries.value.splice(index, 1)
    }
  }

  function removeFailedResult(index: number) {
    if (index >= 0 && index < failedRecoveries.value.length) {
      failedRecoveries.value.splice(index, 1)
    }
  }

  function clearError() {
    error.value = null
  }

  function cancelRecovery() {
    if (isRecovering.value) {
      // This would need to be implemented in the recovery engine
      // For now, just reset the state
      isRecovering.value = false
      currentTask.value = null
      progress.value = 0
      totalTasks.value = 0
    }
  }

  // Helper functions
  function createRecoveryTask(
    versionId: string,
    fileId: string,
    originalPath: string,
    targetPath: string
  ): RecoveryTask {
    return {
      versionId,
      fileId,
      originalPath,
      targetPath
    }
  }

  function getTaskSummary(task: RecoveryTask): string {
    return `${task.originalPath} → ${task.targetPath}`
  }

  return {
    // State
    recoveryQueue,
    completedRecoveries,
    failedRecoveries,
    isRecovering,
    currentTask,
    progress,
    totalTasks,
    error,
    recoveryHistory,
    defaultOptions,
    batchOptions,
    previewData,
    conflicts,
    
    // Getters
    hasQueuedTasks,
    hasCompletedTasks,
    hasFailedTasks,
    successRate,
    queueSummary,
    recentRecoveries,
    
    // Actions
    addToQueue,
    addMultipleToQueue,
    removeFromQueue,
    clearQueue,
    recoverSingle,
    recoverBatch,
    previewRecovery,
    updateProgress,
    updateDefaultOptions,
    updateBatchOptions,
    clearResults,
    clearHistory,
    retryFailed,
    removeCompletedResult,
    removeFailedResult,
    clearError,
    cancelRecovery,
    
    // Helpers
    createRecoveryTask,
    getTaskSummary
  }
})